package rcproxy

import (
	"fmt"
	"net"
)

type RCProxy struct {
	Shellrs map[string]*Shellr //	Shellr 对象列表
}

func NewRCProxy() *RCProxy {
	sm := new(RCProxy)
	sm.Shellrs = make(map[string]*Shellr)
	return sm
}

// RegisterShellr 用于注册一个 Shellr 对象
func (sm *RCProxy) RegisterShellr(shellr *Shellr) error {
	//if _, exist := sm.Shellrs[shellr.Name]; exist {
	//	return fmt.Errorf("the Shell with the same address '%v' aleady exist", shellr.Name)
	//}
	sm.Shellrs[shellr.Name] = shellr
	return nil
}

// UnregisterShellr 用于注册一个 Shellr 对象；如果注册成功，将返回注册对象的唯一编号；如果注册失败，返回 -1；
func (sm *RCProxy) UnregisterShellr(name string) {
	//	找到 Shellr 对象并删除
	_, exist := sm.Shellrs[name]
	if !exist {
		return
	}
	delete(sm.Shellrs, name)
}

func (sm *RCProxy) Find(name string) (*Shellr, error) {
	sh, exist := sm.Shellrs[name]
	if exist {
		return sh, nil
	}

	return nil, fmt.Errorf("unknown target %s", name)
}

func (sm *RCProxy) EnumShellr(callback func(name string, addr net.Addr) int) {
	for _, sh := range sm.Shellrs {
		if callback(sh.Name, sh.conn.RemoteAddr()) != 0 {
			break
		}
	}
}
